package com.zeji.androidadvance.activity.touchFollow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;

public class TouchFollowView extends View {
    int lastX;
    int lastY;

    public TouchFollowView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        int maxRight = ((View) getParent()).getWidth();
        int maxBottom = ((View) getParent()).getHeight();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                lastX = x;
                lastY = y;
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                int offsetX = x - lastX;
                int offsetY = y - lastY;
                // 使用layout方式
                int left = getLeft() + offsetX;
                int top = getTop() + offsetY;
                int right = getRight() + offsetX;
                int bottom = getBottom() + offsetY;
                left = Math.min(maxRight - getWidth(), Math.max(0, left));
                right = Math.min(maxRight, Math.max(getWidth(), right));
                top = Math.min(maxBottom - getHeight(), Math.max(0, top));
                bottom = Math.min(maxBottom, Math.max(getHeight(), bottom));
                layout(left, top, right, bottom);
                // 其他还有 offset，属性动画，scroller，scrollTo/By 方式
                break;
            }
            case MotionEvent.ACTION_UP: {
                lastX = 0;
                lastY = 0;
                break;
            }
        }
        return true;
    }
}
